package core.tool.bpe;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;

import apps.reading.ReadingSpider;

import core.tool.log.log4j.EasyLogger;
import core.tool.scan.ScanService;
import core.tool.xml.dom4j.jaxb.XmlHelper;



public abstract class Action {
	
	private static Map<String,Action> actionMap=null;
	protected boolean executeAction(BpeContext bpeContext) {
		EasyLogger.debug("执行节点："+bpeContext.getElement().attribute("name"));
		boolean success=execute(bpeContext);
		runNext(bpeContext);
		return false;
	}
	
	protected abstract boolean execute(BpeContext bpeContext);
	
	private String runNext(BpeContext bpeContext) {
		
		Element nextElement=getNextElement(bpeContext.getDocument(),bpeContext.getElement());
		if(nextElement==null) {
			EasyLogger.debug("后续节点为空，执行结束");
			return null;
		}
		String next=XmlHelper.getElementAttribute(nextElement, "type");
		Action nextAction=getAction(next);
		if(nextAction!=null) {
			bpeContext.setElement(nextElement);
			nextAction.executeAction(bpeContext);
		}else {
			EasyLogger.debug("后续节点为空，执行结束");
		}
		return null;
	}
	
	private Element getNextElement(Document document,Element element) {
		String next=XmlHelper.getElementAttribute(element, "next");
		XmlHelper xmlHelper=new XmlHelper(document);
		Element nextElement=xmlHelper.getElementByAttrXpath("Build/Actions/Action[@name='"+next+"']");
		return nextElement;
	}	
	
	private  Action getAction(String type) {
		ScanService sacnService=new ScanService();
		sacnService.scanPackage("core.tool.bpe.action", ActionType.class);
		List<Object> annoList=sacnService.annotationList;
		for(Object object:annoList) {
			Class cla=object.getClass();
			Annotation[] classAnnotations=cla.getAnnotations();		
			for(Annotation annotation : classAnnotations) {
				if(annotation.annotationType()==ActionType.class) {
					ActionType actionType=(ActionType) annotation;
					if(actionType.value().equals(type)) {
						return (Action) object;
					}
				}
			}			
		}
		return null;
	}
	

	
}
